/*******************************************************************************
 * Copyright (c) 2007, Geophysical Center RAS
 * Sergey Berezin, Dmitry Voitsekhovskiy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * - Neither the name of the Geophysical Center RAS nor the names
 * of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Globalization;
using System.Configuration;

using DAI.ClientToolkit;
using VisualEsse.DataEngine.Types;
using System.Diagnostics;

namespace VisualEsse.DataEngine
{
    public class EsseDataSource
    {
        static protected bool traceCompressed;
        static protected bool traceUncompressed;

        static EsseDataSource()
        {
            try
            {
                AppSettingsReader apr = new AppSettingsReader();
                traceCompressed = (bool)apr.GetValue("VisualEsse.EnableTraceCompressed", typeof(bool));
                traceUncompressed = (bool)apr.GetValue("VisualEsse.EnableTraceUncompressed", typeof(bool));
            }
            catch (Exception)
            {
                traceCompressed = false;
                traceUncompressed = false;
            }
        }

        static public UniformScalarField2d GetDataFieldLocalTest(string parameterName,
            double latMin, double latMax, int latPoints,
            double longMin, double longMax, int longPoints,
            DateTime when)
        {
            IUniformGrid2d grid = GetDataGrid(latMin, latMax, latPoints,
                longMin, longMax, longPoints);

            ScalarArray2d values = new ScalarArray2d(longPoints, latPoints);
            double[,] data = values.Data;

            double lat, lon;
            double lonStep = (longMax - longMin) / (longPoints - 1);
            double latStep = (latMax - latMin) / (latPoints - 1);
            double peaksN1 = 3;
            double peaksN2 = 2;

            for (int j = 0; j < longPoints; j++)
            {
                lon = longMin + j * lonStep;
                for (int i = 0; i < latPoints; i++)
                {
                    lat = latMin + i * latStep;
                    data[j, i] = Math.Sin((lon + 180) / 360.0 * Math.PI * 2 * peaksN1)
                                * Math.Sin((lat + 90) / 180.0 * Math.PI * 2 * peaksN2);
                }
            }

            return new UniformScalarField2d(grid, values);
        }

        static public UniformScalarField2d GetDataField(EsseParameter parameter,
            double latMin, double latMax, int latPoints,
            double longMin, double longMax, int longPoints,
            DateTime when)
        {
            ScalarArray2d values = GetDataArray(parameter, latMin, latMax, latPoints,
                longMin, longMax, longPoints, when);
            IUniformGrid2d grid = GetDataGrid(latMin, latMax, latPoints,
                longMin, longMax, longPoints);
            return new UniformScalarField2d(grid, values);
        }

        static public UniformGrid2d GetDataGrid(double latMin, double latMax, int latPoints,
            double longMin, double longMax, int longPoints)
        {
            double longStep = (longMax - longMin) / (longPoints - 1);
            double latStep = (latMax - latMin) / (latPoints - 1);
            return new UniformGrid2d(
                new UniformGrid1d(longPoints, longMin, longStep),
                new UniformGrid1d(latPoints, latMin, latStep));
        }

        static public double[] GetDataArray(EsseParameter parameter, double lat, double lon, DateTime start, DateTime stop, int minutesStep)
        {
            string url = "http://devel.wdcb.ru/esse/Service.asmx"; // TODO: Store in settings
            DataService dai = new DataService(url);
            string resourceName = "EsseResource"; // TODO: Store in settings
            Console.WriteLine("DAI service {0}\nVersion:{1}\nEsse Data Resource Service {0}\n", url, dai.Version, resourceName);
            DataServiceResource esse = dai.DataServiceResource(resourceName);
            Console.WriteLine("Supported activities:\n" + string.Join("\n", esse.Activities));

            int latPoints = 1;
            int longPoints = 1;

            // List of activities
            object[] activities = new object[2];

            // Prepare first activity
            object[] ap = new object[5 + latPoints * longPoints];
            ap[0] = new GetXmlDataActivityTypeOutput("XmlData" + parameter.ToString());
            ap[1] = new GetXmlDataActivityTypeValue("source", "ncep25");
            string fromString = start.Year.ToString() + "-" + start.Month.ToString() + "-" + start.Day.ToString();
            string toString = stop.Year.ToString() + "-" + stop.Month.ToString() + "-" + stop.Day.ToString();
            ap[2] = new GetXmlDataActivityTypeRange("time", fromString, toString, minutesStep.ToString(System.Globalization.CultureInfo.InvariantCulture));
            ap[3] = new GetXmlDataActivityTypeValue("parameter", parameter.FullName);
            ap[4] = new GetXmlDataActivityTypeValue("level", "0");
            int iap = 5;

            for (int ilat = 0; ilat < latPoints; ilat++)
            {
                for (int ilon = 0; ilon < longPoints; ilon++)
                {
                    ap[iap++] = new GetXmlDataActivityTypeValue("point",
                        string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:f1} {1:f1}",
                                        lat, lon));
                }
            }
            activities[0] = new GetXmlDataActivityType("DataToXml" + parameter.ToString(), ap);

            // Prepare second activity
            activities[1] = new GZIPCompressionType("gzip" + parameter.ToString(), "XmlData" + parameter.ToString(),
                "XmlDataCompressed" + parameter.ToString(), GZIPCompressionTypeSettingsChecksum.adler32);

            Console.WriteLine("Activity list prepared. Starting service call...\n");
            XmlElement resp = esse.Perform(new PerformType(null, null, activities));

            if (/*traceCompressed*/true)
            {
                DateTime now = DateTime.Now;
                StreamWriter traceOutput = new StreamWriter("rsp_comp_" +
                    now.Hour + "_" + now.Minute + "_" + now.Second + ".xml");
                traceOutput.Write(resp.OuterXml);
                traceOutput.Close();
            }

            XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
            ns.AddNamespace("types", "http://ogsadai.org.uk/namespaces/2005/10/types");


            // Console.WriteLine(resp.OuterXml);
            string result = ((XmlElement)resp.SelectSingleNode("//types:result[@name='XmlDataCompressed" + parameter + "']", ns)).InnerText;


            if (/*traceUncompressed*/true)
            {
                StreamReader sr = new StreamReader(new System.IO.Compression.GZipStream(
                                       new System.IO.MemoryStream(Convert.FromBase64String(result)),
                                       System.IO.Compression.CompressionMode.Decompress));
                DateTime now = DateTime.Now;
                StreamWriter traceOutput = new StreamWriter("rsp_" +
                    now.Hour + "_" + now.Minute + "_" + now.Second + ".xml");
                traceOutput.Write(sr.ReadToEnd());
                traceOutput.Close();
            }

            XmlReader xr = XmlReader.Create(new System.IO.StreamReader(
                                   new System.IO.Compression.GZipStream(
                                       new System.IO.MemoryStream(Convert.FromBase64String(result)),
                                       System.IO.Compression.CompressionMode.Decompress)));

            double[] resultData = new double[(int)(((TimeSpan)stop.Subtract(start)).TotalMinutes / minutesStep)];

            for (int i = 0; i < resultData.Length; i++)
            {
                if (!xr.ReadToFollowing("v"))
                    throw new Exception(string.Format("Wrong response. Element v is not found for time {0}", i));


                string valueString = xr.ReadString();
                resultData[i] = Double.Parse(valueString);
            }

            return resultData;
        }

        static public ScalarArray2d GetDataArray(EsseParameter parameter,
            double latMin, double latMax, int latPoints,
            double longMin, double longMax, int longPoints,
            DateTime when)
        {
            // TODO: read from settings
            string url = "http://teos1.wdcb.ru/axis/services/ogsadai/EsseService";//VisualEsse.Plugins.Properties.Settings.Default.DataServiceUrl;
            DataService dai = new DataService(url);
            string resourceName = "EsseResource";//VisualEsse.Plugins.Properties.Settings.Default.DataServiceResource;
            //Console.WriteLine("DAI service {0}\nVersion:{1}\nEsse Data Resource Service {0}\n", url, dai.Version, resourceName);
            DataServiceResource esse = dai.DataServiceResource(resourceName);
            //Console.WriteLine("Supported activities:\n" + string.Join("\n", esse.Activities));


            // List of activities
            object[] activities = new object[2];

            // Prepare first activity
            object[] ap = new object[5 + latPoints * longPoints];
            ap[0] = new GetXmlDataActivityTypeOutput("XmlData" + parameter.ToString());
            ap[1] = new GetXmlDataActivityTypeValue("source", "ncep25");
            string fromString = when.Year.ToString() + "-" + when.Month.ToString() + "-" + when.Day.ToString();
            string toString = when.Year.ToString() + "-" + when.Month.ToString() + "-" + when.Day.ToString();
            ap[2] = new GetXmlDataActivityTypeRange("time", fromString, toString, "1440");
            ap[3] = new GetXmlDataActivityTypeValue("parameter", parameter.FullName);
            ap[4] = new GetXmlDataActivityTypeValue("level", "0");
            int iap = 5;
            for (int ilat = 0; ilat < latPoints; ilat++)
            {
                for (int ilon = 0; ilon < longPoints; ilon++)
                {
                    ap[iap++] = new GetXmlDataActivityTypeValue("point",
                        string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:f1} {1:f1}",
                        latMin + ilat * (latMax - latMin) / (latPoints - 1),
                        longMin + ilon * (longMax - longMin) / (longPoints - 1)));
                }
            }
            activities[0] = new GetXmlDataActivityType("DataToXml" + parameter.ToString(), ap);

            // Prepare second activity
            activities[1] = new GZIPCompressionType("gzip" + parameter.ToString(), "XmlData" + parameter.ToString(),
                "XmlDataCompressed" + parameter.ToString(), GZIPCompressionTypeSettingsChecksum.adler32);

            //Console.WriteLine("Activity list prepared. Starting service call...\n");
            DateTime start = DateTime.Now;
            XmlElement resp = esse.Perform(new PerformType(null, null, activities));



            DateTime stop = DateTime.Now;
            //Console.WriteLine("Service call completed. Wall clock elapsed time: {0}", stop.Subtract(start));

            XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
            ns.AddNamespace("types", "http://ogsadai.org.uk/namespaces/2005/10/types");


            // Console.WriteLine(resp.OuterXml);
            string result = ((XmlElement)resp.SelectSingleNode("//types:result[@name='XmlDataCompressed" + parameter + "']", ns)).InnerText;

            /*            Console.WriteLine("\n\nDecompressed output:\n");
                        Stream resultStream = new System.IO.Compression.GZipStream(
                            new System.IO.MemoryStream(Convert.FromBase64String(result)),
                            System.IO.Compression.CompressionMode.Decompress);
                        StreamReader sr = new StreamReader(resultStream);
                       Console.WriteLine(sr.ReadToEnd());*/

            ScalarArray2d resultData = new ScalarArray2d(longPoints, latPoints);

            XmlReader xr = XmlReader.Create(new System.IO.StreamReader(
                                   new System.IO.Compression.GZipStream(
                                       new System.IO.MemoryStream(Convert.FromBase64String(result)),
                                       System.IO.Compression.CompressionMode.Decompress)));

            if (!xr.ReadToFollowing("v"))
                throw new Exception("Wrong response. Element v is not found");

            string valueString = xr.ReadString();
            //            Console.WriteLine(valueString);

            string[] values = valueString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (values.Length != latPoints * longPoints)
                throw new Exception("Wrong response. Incorrent number of points");

            int idx = 0;
            for (int i = 0; i < latPoints; i++)
                for (int j = 0; j < longPoints; j++)
                    resultData[j, i] = Double.Parse(values[idx++], CultureInfo.InvariantCulture);

            return resultData;
        }

        static public ScalarArray2d[] GetDataArrayForTheDay(string dataServiceUrl,
            string resource, string dataSource,
            EsseParameterDescription parameter,
            double latMin, double latMax, int latPoints,
            double longMin, double longMax, int longPoints,
            DateTime when, int StepInMinutes)
        {
            // TODO: read from settings
            //string url = "http://teos1.wdcb.ru/axis/services/ogsadai/EsseService";//VisualEsse.Plugins.Properties.Settings.Default.DataServiceUrl;
            string url = dataServiceUrl; //VisualEsse.DataEngine.Properties.Settings.Default.DataServiceUrl;
            DataService dai = new DataService(url);
            string resourceName = resource; //"EsseResource";//VisualEsse.Plugins.Properties.Settings.Default.DataServiceResource;
            string source = dataSource; //VisualEsse.DataEngine.Properties.Settings.Default.DataSource;
            //Console.WriteLine("DAI service {0}\nVersion:{1}\nEsse Data Resource Service {0}\n", url, dai.Version, resourceName);
            DataServiceResource esse = dai.DataServiceResource(resourceName);
            //Console.WriteLine("Supported activities:\n" + string.Join("\n", esse.Activities));


            // List of activities
            object[] activities = new object[2];

            // Prepare first activity
            object[] ap = new object[6 + latPoints * longPoints];
            ap[0] = new GetXmlDataActivityTypeOutput("XmlData"/* + parameter.EsseParameter.ToString()*/);
            ap[1] = new GetXmlDataActivityTypeValue("source", source);

            string fromString = when.ToString("s") + "UTC";
            DateTime to = when.AddDays((double)(24 * 60 - StepInMinutes) / (24 * 60));
            string toString = to.ToString("s") + "UTC";

            ap[2] = new GetXmlDataActivityTypeRange("time", fromString, toString, StepInMinutes.ToString());
            ap[3] = new GetXmlDataActivityTypeValue("name", parameter.Name);
            ap[4] = new GetXmlDataActivityTypeValue("verticalCoord", parameter.VerticalCoord.Name);
            ap[5] = new GetXmlDataActivityTypeValue("level", parameter.Level.ToString());
            int iap = 6;
            for (int ilat = 0; ilat < latPoints; ilat++)
            {
                for (int ilon = 0; ilon < longPoints; ilon++)
                {
                    ap[iap++] = new GetXmlDataActivityTypeValue("point",
                        string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:f1} {1:f1}",
                        latMin + ilat * (latMax - latMin) / (latPoints - 1),
                        longMin + ilon * (longMax - longMin) / (longPoints - 1)));
                }
            }
            activities[0] = new GetXmlDataActivityType("DataToXml"/* + parameter.EsseParameter.ToString()*/, ap);

            // Prepare second activity
            activities[1] = new GZIPCompressionType("gzip" /*+ parameter.EsseParameter.ToString()*/,
                "XmlData" /*+ parameter.EsseParameter.ToString()*/,
                "XmlDataCompressed" /*+ parameter.EsseParameter.ToString()*/, 
                GZIPCompressionTypeSettingsChecksum.adler32);

            //Console.WriteLine("Activity list prepared. Starting service call...\n");
            DateTime start = DateTime.Now;
            XmlElement resp = esse.Perform(new PerformType(null, null, activities));



            DateTime stop = DateTime.Now;
            //Console.WriteLine("Service call completed. Wall clock elapsed time: {0}", stop.Subtract(start));

            XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
            ns.AddNamespace("types", "http://ogsadai.org.uk/namespaces/2005/10/types");           


            // Console.WriteLine(resp.OuterXml);
            string result = ((XmlElement)resp.SelectSingleNode("//types:result[@name='XmlDataCompressed" + "']", ns)).InnerText;

            //if (DataServiceResource.trace.TraceVerbose)
            //{               
            //    Stream resultStream = new System.IO.Compression.GZipStream(
            //        new System.IO.MemoryStream(Convert.FromBase64String(result)),
            //        System.IO.Compression.CompressionMode.Decompress);
            //    StreamReader sr = new StreamReader(resultStream);
            //    string s = sr.ReadToEnd();

            //    Trace.WriteLineIf(DataServiceResource.trace.TraceVerbose, string.Format("{0} Perform Document result:", DateTime.Now));
            //    Trace.WriteLineIf(DataServiceResource.trace.TraceVerbose, s);
            //}

            //Console.WriteLine("\n\nDecompressed output:\n");
            //Stream resultStream = new System.IO.Compression.GZipStream(
            //    new System.IO.MemoryStream(Convert.FromBase64String(result)),
            //    System.IO.Compression.CompressionMode.Decompress);
            //StreamReader sr = new StreamReader(resultStream);
            //Console.WriteLine(sr.ReadToEnd());

            XmlReader xr = XmlReader.Create(new System.IO.StreamReader(
                                   new System.IO.Compression.GZipStream(
                                       new System.IO.MemoryStream(Convert.FromBase64String(result)),
                                       System.IO.Compression.CompressionMode.Decompress)));

            int count = 24 * 60 / StepInMinutes;
            ScalarArray2d[] resultData = new ScalarArray2d[count];

            for (int k = 0; k < count; k++)
            {
                ScalarArray2d a = new ScalarArray2d(longPoints, latPoints);

                if (!xr.ReadToFollowing("v"))
                    throw new Exception("Wrong response. Element v is not found");

                string valueString = xr.ReadString();

                string[] values = valueString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (values.Length != latPoints * longPoints)
                    throw new Exception("Wrong response. Incorrent number of points");

                int idx = 0;
                double[,] data = a.Data;
                for (int i = 0; i < latPoints; i++)
                    for (int j = 0; j < longPoints; j++)
                        data[j, i] = Double.Parse(values[idx++], CultureInfo.InvariantCulture);
                resultData[k] = a;
            }

            return resultData;
        }

        //static public ScalarArray2d[] GetDataArrayForTheDay(EsseParameterDescription parameter,
        //    double latMin, double latMax, int latPoints,
        //    double longMin, double longMax, int longPoints,
        //    DateTime when, int StepInMinutes)
        //{
        //    // TODO: read from settings
        //    //string url = "http://teos1.wdcb.ru/axis/services/ogsadai/EsseService";//VisualEsse.Plugins.Properties.Settings.Default.DataServiceUrl;
        //    string url = VisualEsse.DataEngine.Properties.Settings.Default.DataServiceUrl;
        //    DataService dai = new DataService(url);
        //    string resourceName = "EsseResource";//VisualEsse.Plugins.Properties.Settings.Default.DataServiceResource;
        //    string source = VisualEsse.DataEngine.Properties.Settings.Default.DataSource;
        //    //Console.WriteLine("DAI service {0}\nVersion:{1}\nEsse Data Resource Service {0}\n", url, dai.Version, resourceName);
        //    DataServiceResource esse = dai.DataServiceResource(resourceName);
        //    //Console.WriteLine("Supported activities:\n" + string.Join("\n", esse.Activities));


        //    // List of activities
        //    object[] activities = new object[2];

        //    // Prepare first activity
        //    object[] ap = new object[5 + latPoints * longPoints];
        //    ap[0] = new GetXmlDataActivityTypeOutput("XmlData" + parameter.EsseParameter.ToString());
        //    ap[1] = new GetXmlDataActivityTypeValue("source", source);

        //    string fromString = when.ToString("s") + "UTC";
        //    DateTime to = when.AddDays((double)(24 * 60 - StepInMinutes) / (24 * 60));
        //    string toString = to.ToString("s") + "UTC";

        //    ap[2] = new GetXmlDataActivityTypeRange("time", fromString, toString, StepInMinutes.ToString());
        //    ap[3] = new GetXmlDataActivityTypeValue("parameter", parameter.EsseParameter.FullName);
        //    ap[4] = new GetXmlDataActivityTypeValue("level", level);
        //    int iap = 5;
        //    for (int ilat = 0; ilat < latPoints; ilat++)
        //    {
        //        for (int ilon = 0; ilon < longPoints; ilon++)
        //        {
        //            ap[iap++] = new GetXmlDataActivityTypeValue("point",
        //                string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:f1} {1:f1}",
        //                latMin + ilat * (latMax - latMin) / (latPoints - 1),
        //                longMin + ilon * (longMax - longMin) / (longPoints - 1)));
        //        }
        //    }
        //    activities[0] = new GetXmlDataActivityType("DataToXml" + parameter.EsseParameter.ToString(), ap);

        //    // Prepare second activity
        //    activities[1] = new GZIPCompressionType("gzip" + parameter.EsseParameter.ToString(), "XmlData" + parameter.EsseParameter.ToString(),
        //        "XmlDataCompressed" + parameter.EsseParameter.ToString(), GZIPCompressionTypeSettingsChecksum.adler32);

        //    //Console.WriteLine("Activity list prepared. Starting service call...\n");
        //    DateTime start = DateTime.Now;
        //    XmlElement resp = esse.Perform(new PerformType(null, null, activities));



        //    DateTime stop = DateTime.Now;
        //    //Console.WriteLine("Service call completed. Wall clock elapsed time: {0}", stop.Subtract(start));

        //    XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
        //    ns.AddNamespace("types", "http://ogsadai.org.uk/namespaces/2005/10/types");


        //    // Console.WriteLine(resp.OuterXml);
        //    string result = ((XmlElement)resp.SelectSingleNode("//types:result[@name='XmlDataCompressed" + parameter.EsseParameter + "']", ns)).InnerText;

        //    //if (DataServiceResource.trace.TraceVerbose)
        //    //{               
        //    //    Stream resultStream = new System.IO.Compression.GZipStream(
        //    //        new System.IO.MemoryStream(Convert.FromBase64String(result)),
        //    //        System.IO.Compression.CompressionMode.Decompress);
        //    //    StreamReader sr = new StreamReader(resultStream);
        //    //    string s = sr.ReadToEnd();

        //    //    Trace.WriteLineIf(DataServiceResource.trace.TraceVerbose, string.Format("{0} Perform Document result:", DateTime.Now));
        //    //    Trace.WriteLineIf(DataServiceResource.trace.TraceVerbose, s);
        //    //}

        //    //Console.WriteLine("\n\nDecompressed output:\n");
        //    //Stream resultStream = new System.IO.Compression.GZipStream(
        //    //    new System.IO.MemoryStream(Convert.FromBase64String(result)),
        //    //    System.IO.Compression.CompressionMode.Decompress);
        //    //StreamReader sr = new StreamReader(resultStream);
        //    //Console.WriteLine(sr.ReadToEnd());

        //    XmlReader xr = XmlReader.Create(new System.IO.StreamReader(
        //                           new System.IO.Compression.GZipStream(
        //                               new System.IO.MemoryStream(Convert.FromBase64String(result)),
        //                               System.IO.Compression.CompressionMode.Decompress)));

        //    int count = 24 * 60 / StepInMinutes;
        //    ScalarArray2d[] resultData = new ScalarArray2d[count];

        //    for (int k = 0; k < count; k++)
        //    {
        //        ScalarArray2d a = new ScalarArray2d(longPoints, latPoints);

        //        if (!xr.ReadToFollowing("v"))
        //            throw new Exception("Wrong response. Element v is not found");

        //        string valueString = xr.ReadString();

        //        string[] values = valueString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        //        if (values.Length != latPoints * longPoints)
        //            throw new Exception("Wrong response. Incorrent number of points");

        //        int idx = 0;
        //        double[,] data = a.Data;
        //        for (int i = 0; i < latPoints; i++)
        //            for (int j = 0; j < longPoints; j++)
        //                data[j, i] = Double.Parse(values[idx++], CultureInfo.InvariantCulture);
        //        resultData[k] = a;
        //    }

        //    return resultData;
        //}
    }
}

